package com.jky.trial.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.jky.trial.common.BaseResult;
import com.jky.trial.common.ExportUtil;
import com.jky.trial.common.ListResult;
import com.jky.trial.common.Pagination;
import com.jky.trial.constant.DataStatus;
import com.jky.trial.constant.PermissionConstant;
import com.jky.trial.entity.*;
import com.jky.trial.mapper.CategoryMapper;
import com.jky.trial.mapper.RelationMapper;
import com.jky.trial.mapper.UserMapper;
import com.jky.trial.service.CategoryService;
import com.jky.trial.service.MsgService;
import com.jky.trial.service.ProjectService;
import com.jky.trial.service.RelationService;
import com.jky.trial.vo.CategoryVo;
import com.jky.trial.vo.UserVo;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.ss.util.CellRangeAddress;
import org.apache.poi.xssf.usermodel.*;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.ServletOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.text.DecimalFormat;
import java.util.Date;
import java.util.List;
import java.util.concurrent.atomic.AtomicBoolean;

@Service
@Slf4j
public class CategoryServiceImpl implements CategoryService {
    private final CategoryMapper recordMapper;
    private final UserMapper userMapper;
    private final RelationMapper relationMapper;
    private final ProjectService projectService;
    private final MsgService msgService;
    private RelationService relationService;

    @Autowired
    CategoryServiceImpl(
            RelationService relationService,
            UserMapper userMapper,
            MsgService msgService, RelationMapper relationMapper, CategoryMapper recordMapper, ProjectService projectService) {
        this.relationService = relationService;
        this.msgService = msgService;
        this.userMapper = userMapper;
        this.recordMapper = recordMapper;
        this.relationMapper = relationMapper;
        this.projectService = projectService;
    }

    @Override
    public int save(Category record) {
        return recordMapper.insertSelectiveWithId(record);
    }

    @Override
    public Category selectOne(Category record) {
        return recordMapper.selectOne(record);
    }

    @Override
    public Category selectLatestOne(Category record) {
        return recordMapper.selectLatestOne(record);
    }

    @Override
    public ListResult zjList(CategoryVo record) {
        List<CategoryVo> list = recordMapper.selectZj(record);
        list.forEach(item -> {
            Relation relation = new Relation();
            relation.setSourceId(item.getId());
            relation.setType(DataStatus.RELATION_TYPE_JZ_DESCER.getVal());
            relation.setRemark("target_id");
            item.setUsers(userMapper.listByRelation(relation));
            ;
        });
        ListResult res = new ListResult(true, list);
        res.setPage(new Pagination(
                record.getPage(),
                (int) count(record),
                record.getSize()
        ));
        return res;
    }

    @Override
    public List<CategoryVo> listByDr(CategoryVo record) {
        record.setDeleted(false);
        return recordMapper.listByDr(record);
    }

    @Override
    public Category selectZjzByDescer(CategoryVo record) {
        return recordMapper.selectZjzByDescer(record);
    }

    /***
     * 土分析试验委托书
     * @param record
     * @param outputStream
     * @return
     */
    public OutputStream exportExcel(CategoryVo record, ServletOutputStream outputStream, String dutyName) {

        // 创建一个workbook 对应一个excel应用文件
        XSSFWorkbook workBook = new XSSFWorkbook();
        // 在workbook中添加一个sheet,对应Excel文件中的sheet
        XSSFSheet sheet = workBook.createSheet(record.getName());
        sheet.setDisplayGridlines(false);//不显示网格
        ExportUtil exportUtil = new ExportUtil(workBook, sheet);
        XSSFCellStyle headStyle = exportUtil.getHeadStyle();
        XSSFCellStyle bodyStyle = exportUtil.getBodyStyle();
        XSSFCellStyle bodyNoBorderStyle = exportUtil.getBodyTitleStyleWith();
        // 构建表头
        XSSFRow headerRow = sheet.createRow(0);
        XSSFRow lineRow1 = sheet.createRow(1);
        XSSFRow lineRow2 = sheet.createRow(2);
        XSSFRow lineRow3 = sheet.createRow(3);
        XSSFRow head1Row = sheet.createRow(4);
        XSSFRow head2Row = sheet.createRow(5);
        String remark2 = record.getRemark2();
        JSONObject remark2Obj = JSONObject.parseObject(remark2);
        JSONArray remark2Header1Obj = JSONObject.parseArray(remark2Obj.getString("header1"));
        JSONArray remark2Header2Obj = JSONObject.parseArray(remark2Obj.getString("header2"));
        JSONArray remark2Data12Obj = JSONObject.parseArray(remark2Obj.getString("datas1"));
        JSONArray settingData = JSONObject.parseArray(remark2Obj.getString("settingData")).getJSONArray(0); //
        int total = remark2Header2Obj.size();//总列数
        lineRow3.setHeightInPoints(24);
        lineRow1.setHeightInPoints(24);
        lineRow2.setHeightInPoints(24);
        XSSFCell cell = null;
        XSSFCell cell2 = null;
        XSSFCell cell1 = null;
        //一、二级表头赋值
        for (int i = 0; i < remark2Header2Obj.size(); i++) {
            cell2 = head2Row.createCell(i);
            cell1 = head1Row.createCell(i);
            JSONObject data = JSON.parseObject(remark2Header2Obj.get(i).toString());
            cell1.setCellValue(data.get("title").toString());
            cell2.setCellValue(data.get("title").toString());
            cell2.setCellStyle(bodyStyle);
            cell1.setCellStyle(headStyle);
            headerRow.createCell(i);//.setCellStyle(bodyNoBorderStyle);
            lineRow1.createCell(i).setCellStyle(bodyNoBorderStyle);
            lineRow2.createCell(i).setCellStyle(bodyNoBorderStyle);
            lineRow3.createCell(i).setCellStyle(bodyNoBorderStyle);
        }
        CellRangeAddress headerRange = new CellRangeAddress(0, 0, 1, remark2Header2Obj.size() - 2);//起始行,结束行,起始列,结束列
        sheet.addMergedRegion(headerRange);  //合并单元格
        //设置标题
        headerRow.getCell(1).setCellValue("土   分   析   委   托   书");
        headerRow.setRowStyle(exportUtil.getBorderTopStyle());
        for (int i = 1; i < total - 1; i++) {
            headerRow.getCell(i).setCellStyle(exportUtil.getHeaderStyle());
        }
        headerRow.getCell(0).setCellStyle(exportUtil.getBorderTopLeftStyle());
        headerRow.getCell(total - 1).setCellStyle(exportUtil.getBorderTopRightStyle());
        headerRow.setHeightInPoints(40);
        BigDecimal nine = BigDecimal.valueOf(11);
        //工程名称
        int item1 = (int) ((BigDecimal.valueOf(4).divide(nine, 5, RoundingMode.CEILING)).floatValue() * total);
        if (0 != (item1 + 1)) {
            CellRangeAddress valueRange = new CellRangeAddress(1, 1, 0, item1 + 1);
            sheet.addMergedRegion(valueRange);
        }
        lineRow1.getCell(0).setCellValue("工程名称：" + record.getProjectName());

        //委托单位
        if (0 != (item1 + 1)) {
            CellRangeAddress valueRange = new CellRangeAddress(2, 2, 0, item1 + 1);
            sheet.addMergedRegion(valueRange);
        }
        lineRow2.getCell(0).setCellValue("委托单位：" + record.getName());

        //审核人
        if (0 != (item1 + 1)) {
            CellRangeAddress valueRange = new CellRangeAddress(3, 3, 0, item1 + 1);
            sheet.addMergedRegion(valueRange);
        }
        lineRow3.getCell(0).setCellValue("审核人：" + settingData.getString(3).replaceAll("\\d+", ""));

        //依据标准
        int item2 = (int) ((BigDecimal.valueOf(6).divide(nine, 5, RoundingMode.CEILING)).floatValue() * total);
        if (item2 != total - 1) {
            CellRangeAddress label2Range = new CellRangeAddress(1, 1, item2, total - 1);
            sheet.addMergedRegion(label2Range);
        }
        lineRow1.getCell(item2).setCellValue("依据标准：" + settingData.getString(2));

        //工程负责人(委托人)
        if (item2 != total - 1) {
            CellRangeAddress label2Range = new CellRangeAddress(3, 3, item2, total - 1);
            sheet.addMergedRegion(label2Range);
        }
        lineRow3.getCell(item2).setCellValue("工程负责人(委托人)：" + dutyName);

        //委托日期
        if (item2 != (total - 1)) {
            CellRangeAddress label2Range = new CellRangeAddress(2, 2, item2, total - 1);
            sheet.addMergedRegion(label2Range);
        }
        lineRow2.getCell(item2)
                .setCellValue("委托日期：" + settingData.getString(0).substring(0, 10) + "      完成日期：" + settingData.getString(1).substring(0, 10))
        ;
        //一级表头合并、赋值、设置列宽
        for (int i = 0, j = 0; i < remark2Header1Obj.size(); i++) {
            JSONObject data = JSON.parseObject(remark2Header1Obj.get(i).toString());
            int len = Integer.valueOf(data.get("colspan").toString());
            cell = head1Row.getCell(j);
            if (len == 1 && data.get("title").toString().equals("")) {//不包含二级表头的列
                CellRangeAddress cellRangeAddress = new CellRangeAddress(4, 5, j, j);//起始行,结束行,起始列,结束列
                sheet.addMergedRegion(cellRangeAddress);
                JSONObject dataHeader1 = JSON.parseObject(remark2Header2Obj.get(j).toString());
                cell.setCellValue(dataHeader1.get("title").toString());
            } else { //包含2级表头列
                if (len != 1) {
                    CellRangeAddress cellRangeAddress = new CellRangeAddress(4, 4, j, j + len - 1);//起始行,结束行,起始列,结束列
                    sheet.addMergedRegion(cellRangeAddress);
                }
                cell.setCellValue(data.get("title").toString());
            }
            j += len;
        }
        // 构建表体数据
        for (int j = 0; j < remark2Data12Obj.size(); j++) {
            XSSFRow bodyRow = sheet.createRow(j + 6);
            bodyRow.setHeightInPoints(25);
            JSONArray rowDatas = JSONObject.parseArray(remark2Data12Obj.get(j).toString());
            for (int k = 0; k < rowDatas.size(); k++) {
                if (j == 0) {
                    int totalWidth = 90;
                    int totalCol = total;
                    if (k == 0) {
                        sheet.setColumnWidth(k, (int) ((totalWidth * 256 - (totalCol - 1) * ((BigDecimal.valueOf(totalWidth).divide(BigDecimal.valueOf(totalCol), 2, RoundingMode.CEILING)).floatValue() * 256))));
                    } else {
                        sheet.setColumnWidth(k, (int) ((BigDecimal.valueOf(totalWidth).divide(BigDecimal.valueOf(totalCol), 2, RoundingMode.CEILING)).floatValue() * 256));
                    }
                }
                cell = bodyRow.createCell(k);
                cell.setCellStyle(bodyStyle);
                cell.setCellValue(rowDatas.get(k).toString());
            }
        }

        try {
            workBook.write(outputStream);
            outputStream.flush();
            outputStream.close();
            return null;
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                outputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return null;
    }

    /**
     * TODO 除法运算，保留小数
     *
     * @param a 被除数
     * @param b 除数
     * @return 商
     * @author 袁忠明
     * @date 2018-4-17下午2:24:48
     */
    public static Float txfloat(int a, int b) {
        // TODO 自动生成的方法存根

        DecimalFormat df = new DecimalFormat("0.00");//设置保留位数

        return Float.parseFloat(df.format((float) a / b));

    }

    @Transactional
    @Override
    public BaseResult uploadReport(Category record, User user) {
        if (record.getType().equals(DataStatus.CATEGORY_DATA_TYPE_REPORT.getVal()) //试验成果报告
        ) {
            CategoryExample categoryExample = new CategoryExample();
            CategoryExample.Criteria ca = null;
            ca = categoryExample.createCriteria();
            ca.andNameEqualTo(record.getName());//
            ca.andTypeEqualTo(record.getType());
            ca.andComIdEqualTo(record.getComId());//项目ID
            ca.andDeletedEqualTo(false);
            List<Category> list = recordMapper.selectByExample(categoryExample);
            if (list.size() != 0) return new BaseResult(false, "任务书名称重复", 403);
        }

        CategoryVo categoryVo = new CategoryVo();
        categoryVo.setType(DataStatus.CATEGORY_DATA_TYPE_TASK_BOOK.getVal());
        categoryVo.setSize(Integer.MAX_VALUE);
        categoryVo.setComId(record.getComId());
        categoryVo.setDeleted(false);
        List<CategoryVo> list = recordMapper.pageList(categoryVo);
        for (int i = 0; i < list.size(); i++) {
//            Integer taskId = record.getPId();
            Category category = new Category();
            category.setId(list.get(i).getId());
            category.setStatus(record.getStatus());
            recordMapper.updateByPrimaryKeySelective(category); // 变更试验成果报告状态
        }
        record.setStatus(1);//试验成果报告
        recordMapper.insertSelective(record);
        Integer type = 0;
        //确定关系类型
        if (record.getType().equals(DataStatus.CATEGORY_DATA_TYPE_REPORT.getVal())) {
            type = DataStatus.RELATION_TYPE_REPORT_USER.getVal();
        }
        if (type != 0)
            relationService.save(user.getId(), record.getId(), type);
        return new BaseResult(true, record.getId());
    }

    @Override
    public BaseResult create(Category record, User user) {
        if (record.getId() != null) return new BaseResult(true, recordMapper.updateByPrimaryKeySelective(record));
        record.setCreateAt(new Date());

        if (record.getType().equals(DataStatus.CATEGORY_DATA_TYPE_DEP.getVal()) //部门
                || record.getType().equals(DataStatus.CATEGORY_DATA_TYPE_BUS.getVal()) //业务板块
                || record.getType().equals(DataStatus.CATEGORY_DATA_TYPE_COM1.getVal()) //勘察单位
                || record.getType().equals(DataStatus.CATEGORY_DATA_TYPE_COM2.getVal()) //委托单位
                || record.getType().equals(DataStatus.CATEGORY_DATA_TYPE_COM3.getVal()) //施工单位
                || record.getType().equals(DataStatus.CATEGORY_DATA_TYPE_PERSON.getVal()) //业务联系人
                || record.getType().equals(DataStatus.CATEGORY_DATA_TYPE_HUBI.getVal()) //护壁
                || record.getType().equals(DataStatus.CATEGORY_DATA_TYPE_ZUANJIN.getVal()) //钻进
                || record.getType().equals(DataStatus.CATEGORY_DATA_TYPE_ZUANJIN.getVal()) //钻进
                || record.getType().equals(DataStatus.CATEGORY_DATA_TYPE_YANSE.getVal()) //钻进
                || record.getType().equals(DataStatus.CATEGORY_DATA_TYPE_YANTU_CATEGORY.getVal()) //钻进
                || record.getType().equals(DataStatus.CATEGORY_DATA_TYPE_YANTU_NAME.getVal()) //钻进
                || record.getType().equals(DataStatus.CATEGORY_DATA_TYPE_DIZHI_AGE.getVal()) //钻进
                || record.getType().equals(DataStatus.CATEGORY_DATA_TYPE_DIZHI_REASON.getVal()) //钻进
                || record.getType().equals(DataStatus.CATEGORY_DATA_TYPE_DONGTAN_CATEGORY.getVal()) //钻进
                || record.getType().equals(DataStatus.CATEGORY_DATA_TYPE_TUYANG_ZHILIANG_LEVEL.getVal()) //钻进
                || record.getType().equals(DataStatus.CATEGORY_DATA_TYPE_QUSHUI_METHOD.getVal()) //钻进
                || record.getType().equals(DataStatus.CATEGORY_DATA_TYPE_SHIYANG_QUYANG_TOOL_METHOD.getVal()) //钻进
                || record.getType().equals(DataStatus.CATEGORY_DATA_TYPE_DIXIASHUI_CATEGORY.getVal()) //钻进
                || record.getType().equals(DataStatus.CATEGORY_DATA_TYPE_SHIDU.getVal()) //钻进
                || record.getType().equals(DataStatus.CATEGORY_DATA_TYPE_MIDU.getVal()) //钻进
                || record.getType().equals(DataStatus.CATEGORY_DATA_TYPE_ZHUANGTAI.getVal()) //钻进
                || record.getType().equals(DataStatus.CATEGORY_DATA_TYPE_TUYANG_STATUS.getVal()) //钻进
        ) { //部门
            CategoryExample categoryExample = new CategoryExample();
            CategoryExample.Criteria ca = null;
            ca = categoryExample.createCriteria();
            ca.andNameEqualTo(record.getName());//
            ca.andTypeEqualTo(record.getType());
            ca.andDeletedEqualTo(false);
            List<Category> list = recordMapper.selectByExample(categoryExample);
            if (list.size() != 0) return new BaseResult(false, "名称重复", 403);
        }
        if (record.getType().equals(DataStatus.CATEGORY_DATA_TYPE_DEP.getVal())) { //部门
            CategoryExample categoryExample1 = new CategoryExample();
            CategoryExample.Criteria ca1 = null;
            ca1 = categoryExample1.createCriteria();
            ca1.andDeletedEqualTo(false);
            ca1.andTypeEqualTo(record.getType());
            ca1.andRemarkEqualTo(record.getRemark());//
            List<Category> list1 = recordMapper.selectByExample(categoryExample1);
            if (list1.size() != 0) return new BaseResult(false, "编号重复", 403);
        }
        recordMapper.insertSelective(record);
        Integer type = 0;
        //确定关系类型 //DataStatus
        if (record.getType().equals(DataStatus.CATEGORY_DATA_TYPE_BILL.getVal())) {
            type = DataStatus.RELATION_TYPE_BILL_USER.getVal();
        } else if (record.getType().equals(DataStatus.CATEGORY_DATA_TYPE_TASK_BOOK.getVal())) {
            type = DataStatus.RELATION_TYPE_BOOK_USER.getVal();
        } else if (record.getType().equals(DataStatus.CATEGORY_DATA_TYPE_REPORT.getVal())) {
            type = DataStatus.RELATION_TYPE_REPORT_USER.getVal();
        }
        if (type != 0)
            relationService.save(user.getId(), record.getId(), type);
        return new BaseResult(true, record.getId());
    }

    @Override
    public int update(Category record) {
        return recordMapper.updateByPrimaryKeySelective(record);
    }

    @Transactional
    @Override
    public BaseResult submitBill(Category record, User user) {

        Category bill = recordMapper.selectByPrimaryKey(record.getId());
        if (!bill.getStatus().equals(DataStatus.BILL_STATUS_PAPER.getVal()) ||
                !record.getStatus().equals(DataStatus.BILL_STATUS_SUBMIT.getVal())
        ) {
            return new BaseResult(false, "操作异常");
        } //
        Relation relation = new Relation();
        relation.setType(DataStatus.RELATION_TYPE_BILL_SAMPLE.getVal());
        relation.setSourceId(record.getId());
        int total = relationMapper.count(relation);
        if (total == 0) return new BaseResult(false, "该确认单不包含土样，请设置土样后提交！");
        record.setPersonId(user.getId());
        int res = recordMapper.updateByPrimaryKeySelective(record);
        if (res > 0) {
            Category category = new Category();
            category.setName(PermissionConstant.TRIAL);
            List<Relation> list = relationMapper.findRoleByPermissionName(category);
            list.forEach(item -> {
                relationService.save(item.getSourceId(), bill.getId(), DataStatus.RELATION_TYPE_BILL_USER.getVal());

                msgService.sendMsg(
                        user.getId(),
                        item.getSourceId(),
                        "用户" + user.getName() + "提交了样品确认单《" + bill.getName() + "》,请及时查看确认",
                        record.getId(),     //
                        DataStatus.MSG_TYPE_BILL_SUBMIT.getVal()
                );
            });

        }
        return new BaseResult(true, "操作异常", 200);
    }

    /**
     * 发布试验成果报告
     *
     * @param record
     * @param user
     * @return
     */
    @Transactional
    @Override
    public int publishReport(Category record, User user) {
        Category bill = recordMapper.selectByPrimaryKey(record.getId());
        if (!bill.getStatus().equals(DataStatus.REPORT_STATUS_PAPER.getVal()) ||
                !record.getStatus().equals(DataStatus.REPORT_STATUS_SUBMIT.getVal())
        ) {
            return 0;
        } //
        int res = recordMapper.updateByPrimaryKeySelective(record);
        if (res > 0) {
            Category category = new Category();
            category.setName(PermissionConstant.RECEIVE_TRIAL_REPORT);
            Project project = projectService.detail(bill.getComId());//
            List<Relation> list = relationMapper.findRoleByPermissionName(category);
            AtomicBoolean hasTechDirector = new AtomicBoolean(false);
            list.forEach(item -> {
                if (project.getTechDirector().equals(item.getSourceId())) {
                    hasTechDirector.set(true);
                }
                msgService.sendMsg(
                        user.getId(),
                        item.getSourceId(),
                        "用户" + user.getName() + "发布了项目" + project.getName() + "的试验成果报告《" + bill.getName() + "》,请及时查看确认",
                        record.getId(),     //
                        DataStatus.MSG_TYPE_REPORT_PUBLISH.getVal()
                );
            });
            if (!hasTechDirector.get()) {
                msgService.sendMsg(
                        user.getId(),
                        project.getTechDirector(),
                        "用户" + user.getName() + "发布了项目" + project.getName() + "的试验成果报告《" + bill.getName() + "》,请及时查看确认",
                        record.getId(),     //
                        DataStatus.MSG_TYPE_REPORT_PUBLISH.getVal()
                );
            }

        }
        return res;
    }

    /**
     * 提交任务书
     * record.id  任务书Id
     *
     * @param record
     * @param user
     * @return
     */
    @Transactional
    @Override
    public BaseResult submitBook(Category record, User user) {
        Category bill = recordMapper.selectByPrimaryKey(record.getId());
        if (bill.getRemark2() == null || bill.getRemark2().indexOf("header1") == -1) {
            return new BaseResult(false, "请设置完成任务要求");
        }
        if (
                (
                        !bill.getStatus().equals(DataStatus.BOOK_STATUS_PAPER.getVal()) &&
                                !bill.getStatus().equals(DataStatus.BOOK_STATUS_CHECK_REJECT.getVal())
                )
                        ||
                        !record.getStatus().equals(DataStatus.BOOK_STATUS_SUBMIT.getVal())) {
            return new BaseResult(false, "操作异常");
        }
        record.setPersonId(user.getId());
        int res = recordMapper.updateByPrimaryKeySelective(record);
        if (res > 0) {
            Category category = new Category();
            category.setName(PermissionConstant.TRIAL); //发送给试验室人员
            relationService.save(bill.getPId(), bill.getId(), DataStatus.RELATION_TYPE_BOOK_USER.getVal());
            msgService.sendMsg(
                    user.getId(),
                    bill.getPId(),// 审核人Id
                    "用户" + user.getName() + "提交了任务书《" + bill.getName() + "》,请及时查看审核",
                    record.getId(),     //
                    DataStatus.MSG_TYPE_BOOK_SUBMIT.getVal()
            );
        }
        return new BaseResult(true, "ok", 200);
    }

    /**
     * 审核任务书
     *
     * @param record
     * @param user
     * @return
     */
    @Transactional
    public BaseResult checkBook(Category record, User user) {
        String reason = record.getDesc() == null ? "无说明" : record.getDesc();
        record.setDesc(null);
        Category bill = recordMapper.selectByPrimaryKey(record.getId());
        if (!user.getId().equals(bill.getPId())) {
            return new BaseResult(false, "您非指定审核人，无法进行此任务书审核！");
        }
        if (!(bill.getStatus().equals(DataStatus.BOOK_STATUS_SUBMIT.getVal()) &&
                (record.getStatus().equals(DataStatus.BOOK_STATUS_CHECK_REJECT.getVal()) ||
                        record.getStatus().equals(DataStatus.BOOK_STATUS_CHECK_RESOLVE.getVal()))
        )) {
            return new BaseResult(false, "操作非法或已经操作！");
        }

        int res = recordMapper.updateByPrimaryKeySelective(record);
        if (record.getStatus().equals(DataStatus.BOOK_STATUS_CHECK_REJECT.getVal())) { //审核驳回
            //通知提交用户
            msgService.sendMsg(
                    user.getId(),
                    bill.getPersonId(),
                    "审核人" + user.getName() + "驳回了您提交的《" + bill.getName() + "》任务书,驳回说明：" + reason,
                    record.getId(),     //
                    DataStatus.MSG_TYPE_BOOK_CHECK.getVal()
            );
        } else {
            if (res > 0) {
                //通知提交用户
                msgService.sendMsg(
                        user.getId(),
                        bill.getPersonId(),
                        "审核人" + user.getName() + "审核通过您提交的任务书《" + bill.getName() + "》，审核说明：" + reason,
                        record.getId(),     //
                        DataStatus.MSG_TYPE_BOOK_CHECK.getVal()
                );
                Category category = new Category();
                category.setName(PermissionConstant.TRIAL); //发送给试验室人员
                List<Relation> list = relationMapper.findRoleByPermissionName(category);
                //同事试验室人员
                list.forEach(item -> {
                    relationService.save(bill.getId(), item.getSourceId(), DataStatus.RELATION_TYPE_BOOK_USER.getVal());

                    msgService.sendMsg(
                            user.getId(),
                            item.getSourceId(),
                            "用户" + user.getName() + "发送了任务书《" + bill.getName() + "》，请及时进行工作安排",
                            record.getId(),     //
                            DataStatus.MSG_TYPE_BOOK_CHECK.getVal()
                    );
                });

            }
            return new BaseResult(true, "ok", 200);
        }
        return new BaseResult(true, "ok", 200);

    }

    @Override
    public int del(int id) {
        Category category = new Category();
        category.setId(id);
        category.setDeleted(true);

        Category category1 = recordMapper.selectByPrimaryKey(id);
        if (DataStatus.CATEGORY_DATA_TYPE_ROLE.getVal()
                .equals(category1.getType())) {
            //删除账户关联角色
            relationService.delSourceId(id, DataStatus.RELATION_TYPE_USER_ROLE.getVal());
        }
        return recordMapper.updateByPrimaryKeySelective(category);
    }

    @Override
    public Category detail(int id) {
        return recordMapper.selectByPrimaryKey(id);
    }

    @Override
    public CategoryVo billDetail(int id) {
        CategoryVo categoryVo = recordMapper.selectOneByKey(id);
        if (categoryVo.getPersonId() != null) {
            User user = userMapper.selectByPrimaryKey(categoryVo.getPersonId());
            categoryVo.setPersonName(user.getName());//提交人姓名
        }
        return categoryVo;
    }

    @Override
    public CategoryVo moreDetail(int id) {
        CategoryVo categoryVo = recordMapper.selectOneByKey(id);
        Project project = projectService.detail(categoryVo.getComId());
        categoryVo.setProjectName(project.getName());
        return categoryVo;
    }

    @Override
    public List<CategoryVo> list(CategoryVo record) {

        record.setDeleted(false);
        return recordMapper.pageList(record);
    }

    @Override
    public ListResult page(CategoryVo record) {
        if (record.getStatusList() != null && record.getStatusList().size() == 0) {
            record.setStatusList(null);
        }
        List<CategoryVo> list = list(record);
        ListResult res = new ListResult(true, list);
        res.setPage(new Pagination(
                record.getPage(),
                (int) count(record),
                record.getSize()
        ));
        return res;
    }


    @Override
    public ListResult pageWithPerson(CategoryVo record) {
        record.setDeleted(false);
        record.setPersonType(DataStatus.CATEGORY_DATA_TYPE_PERSON.getVal());
        List<CategoryVo> list = recordMapper.pageListWithPerson(record);
        ListResult res = new ListResult(true, list);
        res.setPage(new Pagination(
                record.getPage(),
                (int) count(record),
                record.getSize()
        ));
        return res;
    }

    @Override
    public ListResult pageWithProject(CategoryVo record) {
        if (record.getStatusList() != null && record.getStatusList().size() == 0) {
            record.setStatusList(null);
        }

        record.setDeleted(false);
        List<CategoryVo> list = recordMapper.pageListWithProject(record);
        if (Integer.valueOf(1).equals(record.getIsAssign())) { //试验室已分配
            list.forEach(item -> { //查询设置用户
                Relation record1 = new Relation();
                record1.setType(record.getType());
                record1.setSourceId(item.getId());
                record1.setRemark("target_id");
                List<UserVo> list1 = userMapper.listByRelation(record1);
                item.setAssigners(list1);
            });
        }
        ListResult res = new ListResult(true, list);
        res.setPage(new Pagination(
                record.getPage(),
                (int) count(record),
                record.getSize()
        ));
        return res;
    }

    @Override
    public ListResult withProjectByPermission(CategoryVo record, User user) {
        Subject subject = SecurityUtils.getSubject();//
        user = userMapper.selectByPrimaryKey(user.getId());

        if (subject.isPermitted(PermissionConstant.COM_PROJECT)) {
            return pageWithProject(record);//
        } else if (subject.isPermitted(PermissionConstant.BUS_PROJECT)) {
            record.setBusId(user.getBusId());
        } else if (subject.isPermitted(PermissionConstant.DEP_PROJECT)) {
            record.setDepId(user.getDepId());
        } else {
            record.setOwnerId(user.getId());
        }
        record.setDeleted(false);
        if (record.getType().equals(DataStatus.CATEGORY_DATA_TYPE_BILL.getVal()))
            record.setRType(DataStatus.RELATION_TYPE_BILL_USER.getVal());
        if (record.getType().equals(DataStatus.CATEGORY_DATA_TYPE_TASK_BOOK.getVal()))
            record.setRType(DataStatus.RELATION_TYPE_BOOK_USER.getVal());
        if (record.getType().equals(DataStatus.CATEGORY_DATA_TYPE_REPORT.getVal()))
            record.setRType(DataStatus.RELATION_TYPE_REPORT_USER.getVal());
        List<CategoryVo> list = recordMapper.withProjectByPermission(record);
        ListResult res = new ListResult(true, list);
        res.setPage(new Pagination(
                record.getPage(),
                recordMapper.countWithProjectByPermission(record),
                record.getSize()
        ));
        return res;
    }

    @Override
    public long count(CategoryVo record) {
        CategoryExample recordExample = new CategoryExample();
        CategoryExample.Criteria criteria = recordExample.createCriteria();
        criteria.andDeletedEqualTo(false);
        if (record.getSearch() != null) { //按名称搜索
            criteria.andNameLike("%" + record.getSearch() + "%");
        }
        if (record.getStatusList() != null && record.getStatusList().size() != 0) {
            criteria.andStatusIn(record.getStatusList());
        }
        if (record.getPId() != null) {
            criteria.andPIdEqualTo(record.getPId());
        }
        if (record.getType() != null) {
            criteria.andTypeEqualTo(record.getType());
        }
        if (record.getComId() != null) {
            criteria.andComIdEqualTo(record.getComId());
        }
        if (record.getStatus() != null) { //按状态筛选
            criteria.andStatusEqualTo(record.getStatus());
        }
        if (record.getArchive() != null) { //
            criteria.andArchiveEqualTo(record.getArchive());
        }
        if (Integer.valueOf(0).equals(record.getIsAssign())) {
            criteria.andRemarkIsNull();
        }
        if (Integer.valueOf(1).equals(record.getIsAssign())) {
            criteria.andRemarkIsNotNull();
        }
        return recordMapper.countByExample(recordExample);
    }
}
